package com.javaee.wordtree.controller;

import com.javaee.wordtree.common.Result;
import com.javaee.wordtree.entity.MessageWithRagInfo;
import com.javaee.wordtree.service.ChatService;
import com.javaee.wordtree.service.MessageService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息控制器
 */
@RestController
@RequestMapping("/chats/{chatId}/messages")
public class MessageController {

    @Resource
    private MessageService messageService;

    @Resource
    private ChatService chatService;

    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    /**
     * 获取聊天的所有消息
     * 
     * @param chatId 聊天ID
     * @return 消息列表
     */
    @GetMapping
    public Result<?> getChatMessages(@PathVariable Integer chatId, HttpServletRequest request) {
        String userId = getCurrentUserId(request);

        // 检查聊天是否属于当前用户
        if (!chatService.isChatBelongToUser(chatId, userId)) {
            return Result.error("-1", "没有权限访问此聊天记录");
        }

        List<MessageWithRagInfo> messages = messageService.getChatMessagesWithRag(chatId);
        return Result.success(messages);
    }

    /**
     * 发送新消息并获取AI回复
     * 
     * @param chatId 聊天ID
     * @param params 请求参数
     * @return AI回复
     */
    @PostMapping
    public Result<?> sendMessage(@PathVariable Integer chatId,
            @RequestBody Map<String, String> params,
            HttpServletRequest request) {
        String userId = getCurrentUserId(request);

        // 检查聊天是否属于当前用户
        if (!chatService.isChatBelongToUser(chatId, userId)) {
            return Result.error("-1", "没有权限操作此聊天记录");
        }

        String content = params.get("content");
        if (content == null || content.isEmpty()) {
            return Result.error("-1", "消息内容不能为空");
        }
        logger.info("收到前端消息，chatId: {}, userId: {}, content: {}", chatId, userId, content);

        // 保存用户消息并生成AI回复
        MessageWithRagInfo aiReply = messageService.saveMessageAndGenerateReply(userId, chatId, content);

        logger.info("发送AI回复，chatId: {}, userId: {}, aiReply: {}", chatId, userId, aiReply.getText());

        return Result.success(aiReply);
    }

    /**
     * 获取当前用户ID（实际应用中应该从JWT或session中获取）
     */
    private String getCurrentUserId(HttpServletRequest request) {
        // 这里简单模拟从请求头中获取用户ID
        String userId = request.getHeader("X-User-ID");
        // 临时使用固定用户ID进行开发测试
        return userId != null ? userId : "123456";
    }
}
